/**
 * @brief 计算cpu总占用率，类似top的效果
*/

#include <cstdint>
#include <fstream>
#include <string>
#include <algorithm>
#include <numeric>
#include <thread>
#include <sstream>
#include <iostream>

void GetCpuTime(int64_t* totalTime, int64_t* useTime) {
    std::string strLine;
    {
        std::ifstream ifs("/proc/stat");
        std::getline(ifs, strLine, '\n');
    }

    std::istringstream istr(strLine);
    std::string cpuName;
    istr>> cpuName;
    constexpr int procStateItemCnt = 10;
    int64_t item_time[procStateItemCnt] = {0};
    for (int i = 0; i < procStateItemCnt; i++) {
        istr>> item_time[i];
    }

    *totalTime = std::accumulate(item_time, item_time + procStateItemCnt, 0);
    *useTime = std::accumulate(item_time, item_time + 3, 0);
}

int main(void)
{
    int64_t lastTotalTime = 0;
    int64_t lastUseTime = 0;

    GetCpuTime(&lastTotalTime, &lastUseTime);
    while (1)
    {
        std::this_thread::sleep_for(std::chrono::seconds(1));

        int64_t totalTime = 0;
        int64_t useTime = 0;
        GetCpuTime(&totalTime, &useTime);

        std::cout<< "cpu usage: " << (useTime - lastUseTime) * 100.0 / (totalTime - lastTotalTime) << "%\n";

        lastTotalTime = totalTime;
        lastUseTime = useTime;
    }

}